#include "buywindow.h"
#include "ui_buywindow.h"
#include<QDebug>
#include<QMessageBox>
/*
 * Date:        2022/11/17
 * Name:        王宇轩
 * Student ID:  20301142
 * Description: 这个类是用户实际的购票窗口，可对乘车段进行选择
*/

int infoNum=7;
BuyWindow::BuyWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::BuyWindow)
{
    ui->setupUi(this);
    this->setFixedSize(this->geometry().size());
    db=new DatabaseFunction();
}

BuyWindow::~BuyWindow()
{
    delete ui;
}


// 初始化车次信息集合
void BuyWindow::initTrainList(QSqlQuery result)
{
   infoNum=0;
   trainList.clearAllItems();
   // 删除位于首位的总列车号
   result.next();
   for(int i=0;result.next();i++){
       trainList.addTrainNum(result.value(0).toString());
       trainList.addStartStation(result.value(1).toString());
       trainList.addEndStation(result.value(2).toString());
       trainList.addStartTime(result.value(3).toString());
       trainList.addEndTime(result.value(4).toString());
       trainList.addLeftTickets(result.value(5).toInt());
       trainList.addPrice(result.value(6).toInt());
       infoNum++;
   }
}

//初始化展示信息
void BuyWindow::initWindowItems()
{
    ui->startComboBox->clear();
    ui->endComboBox->clear();

    for(int i=0;i<infoNum;i++){
        ui->startComboBox->addItem(trainList.getStartStation(i));
        ui->endComboBox->addItem(trainList.getEndStation(i));
    }
    ui->startTime->setText(trainList.getStartTime(0));
    ui->endTime->setText(trainList.getEndTime(0));
    ui->leftTickets->setText(QString::number(trainList.getLeftTickets(0)));
    ui->price->setText(QString::number(trainList.getPrice(0)));
}


void BuyWindow::clearAll()
{
     ui->startComboBox->clear();
     ui->endComboBox->clear();
}

// 接收父界面传递来的火车号，并据此初始化展示信息
void BuyWindow::receiveTrainNum(QString trainNum,QString username)
{
    this->username=username;
    ui->trainNum->setText(trainNum);
    // 根据列车号初始化本界面
    // 起始站、终点站、出发时间、到达时间、余票量、对应价格
    initTrainList(db->getBuyInfo(trainNum));

    initWindowItems();
}

void BuyWindow::on_returnBtn_clicked()
{
    this->close();
}




void BuyWindow::on_startComboBox_currentTextChanged(const QString &arg1)
{
    Q_UNUSED(arg1);
    int nowIndex=ui->startComboBox->currentIndex();
    ui->startTime->setText(trainList.getStartTime(nowIndex));
    ui->endTime->setText(trainList.getEndTime(nowIndex));
    ui->leftTickets->setText(QString::number(trainList.getLeftTickets(nowIndex)));
    ui->price->setText(QString::number(trainList.getPrice(nowIndex)));
}


void BuyWindow::on_endComboBox_currentTextChanged(const QString &arg1)
{
    Q_UNUSED(arg1);
    updateWindowItems();
}

// 用户进行操作后对页面信息进行更新
void BuyWindow::updateWindowItems()
{
    int startIndex=ui->startComboBox->currentIndex();
    int endIndex=ui->endComboBox->currentIndex();
    // 根据当前的起始站和终点站，重新计划起止时间、余票量和价格
    // 如果当前终点站在起始站之后，则没有这班列车
    if(endIndex<startIndex){
        ui->startTime->setText("");
        ui->endTime->setText("");
        ui->leftTickets->setText("");
        ui->price->setText("");
    }else {
        ui->startTime->setText(trainList.getStartTime(startIndex));
        ui->endTime->setText(trainList.getEndTime(endIndex));
        ui->leftTickets->setText(QString::number(computeLeftTickets(startIndex,endIndex)));
        ui->price->setText(QString::number(computePrice(startIndex,endIndex)));
    }
}



// 计算目前剩余的票数，在这里设计出票算法
// 因为没有考虑车座的问题，所以简化问题，让车座的利用率最大化
// 即如果1~3站有人坐了第一个座位然后下车，然后上来的人如果符合下面余票算法
// 则优先做第一个座位
// 查询某一车次号时，首先读取总票数是多少m，看有多少站n，
// 平时只需记录每个站点段的余票数，
// 当想获得某一段的剩余票数时，取min(各段余票数)
// 例如：全线总计5张票，最初没人买，各段之间购票没限制，都是五张票
// 后来1~2剩三张，2~3剩两张，后面忽略。有人想买1~3的，就是两张票
int BuyWindow::computeLeftTickets(int start, int end)
{
    // 获取起始站和终止站的名称。
    int minNum=2000;
    for(int i=start;i<=end;i++){
        if(trainList.getLeftTickets(i)<minNum){
            minNum=trainList.getLeftTickets(i);
        }
    }
    return minNum;
}
// 计算当前起始地点所需要的价格
int BuyWindow::computePrice(int start, int end)
{
    int totalPrice=0;
    for(int i=start;i<=end;i++){
        totalPrice+=trainList.getPrice(i);
    }
    return totalPrice;
}
// 根据购票的起始站和终点站更新途径站点的余票
void BuyWindow::updateLeftTickets(QString trainNum,QString startStation,QString endStation)
{
    QString tempStart=startStation;// 记录临时的起始站
    for (int i = 0; i < infoNum; ++i) {
        // 找到第一个起始站
        if(trainList.getStartStation(i)==tempStart){
            int value=trainList.getLeftTickets(i)-1;
            trainList.setLeftTickets(i,value);
            tempStart=trainList.getEndStation(i);//更新下一个起始站
            // 如果当前起始站等于目标终点站，终止循环，退出函数
            if(tempStart==endStation){
                break;
            }
        }
    }

    // 将更新后的票数写入数据库
    QString sql;
    QSqlQuery sqlQuery;
    for (int i = 0; i < infoNum; ++i) {
        QString start=trainList.getStartStation(i);
        QString end=trainList.getEndStation(i);
        QString leftTickets=QString::number(trainList.getLeftTickets(i));
        sql= QString("update traininfo set leftTickets='%1' "
                     "where trainNum like '%2%' and startStation = '%3' "
                     "and endStation='%4'")
                .arg(leftTickets,trainNum,start,end);
        sqlQuery.exec(sql);
    }
}

// 购买该票
// 根据车次号、起始站、终点站，将对应站点的余票数-1
void BuyWindow::on_buyBtn_clicked()
{
    QString trainNum=ui->trainNum->text();
    QString startStation=ui->startComboBox->currentText();
    QString endStation=ui->endComboBox->currentText();
    QString startTime=ui->startTime->text();
    QString endTime=ui->endTime->text();
    QString price=ui->price->text();

    // 在这里更新剩余的票数
    updateLeftTickets(trainNum,startStation,endStation);

    QString sql=QString("select name,phoneNum,identifyNum from user where username='%1'").arg(username);
    QSqlQuery result(sql);
    result.next();
    QString name=result.value(0).toString();
    QString phoneNum=result.value(1).toString();
    QString idCard=result.value(2).toString();

    sql=QString("insert into ordering(name,phoneNum,idCard,trainNum,startStation,endStation,startTime,endTime,price,isPay)"
                        "values('%1','%2','%3','%4','%5','%6','%7','%8','%9','1')")
            .arg(name,phoneNum,idCard,trainNum,startStation,endStation,startTime,endTime,price);
    if(result.exec(sql)&&db->writeIncomeDB(trainNum,price.toInt())){
        QMessageBox::about(NULL, "提示", "购票成功！");
    }else {
        QMessageBox::critical(NULL, "错误", "购票失败！");
    }
    updateWindowItems();

}

// 收藏按钮，将所选班次放入未支付订单中
void BuyWindow::on_collectBtn_clicked()
{
    QString trainNum=ui->trainNum->text();
    QString startStation=ui->startComboBox->currentText();
    QString endStation=ui->endComboBox->currentText();
    QString startTime=ui->startTime->text();
    QString endTime=ui->endTime->text();
    QString price=ui->price->text();

    QString sql=QString("select name,phoneNum,identifyNum from user where username='%1'").arg(username);
    QSqlQuery result(sql);
    result.next();
    QString name=result.value(0).toString();
    QString phoneNum=result.value(1).toString();
    QString idCard=result.value(2).toString();

    sql=QString("insert into ordering(name,phoneNum,idCard,trainNum,startStation,endStation,startTime,endTime,price,isPay)"
                        "values('%1','%2','%3','%4','%5','%6','%7','%8','%9','0')")
            .arg(name,phoneNum,idCard,trainNum,startStation,endStation,startTime,endTime,price);
    if(result.exec(sql)){
        QMessageBox::about(NULL, "提示", "收藏成功！");
    }else {
        QMessageBox::critical(NULL, "错误", "收藏失败！");
    }
}

